package com.molichuxing.services.infrastructure.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.molichuxing.framework.utils.OssUtil;
import com.molichuxing.framework.utils.PdfToImageUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.services.infrastructure.bean.InsuranceBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.InsuranceMapper;
import com.molichuxing.services.infrastructure.dto.request.create.InsuranceCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.InsuranceModifyDto;
import com.molichuxing.services.infrastructure.dto.response.InsuranceDto;
import com.molichuxing.services.infrastructure.service.InsuranceService;
import com.molichuxing.services.property.CarInsuranceTypeEnum;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 保险 服务实现类
 * </p>
 *
 * @author
 * @since 2019-08-15
 */
@Service("insuranceService")
public class InsuranceServiceImpl implements InsuranceService {

	private static final Logger log = Logger.getLogger(InsuranceServiceImpl.class);

	@Resource
	private InsuranceMapper insuranceMapper;

	@Override
	public Paged<InsuranceDto> getInsurancePage(Map<String, Object> mapParam, Integer pageNum, Integer pageSize) {
		Paged<InsuranceDto> paged = new Paged<>();
		// paged.setTab(getTabList(Integer.parseInt(mapParam.get("type").toString())));
		int count = insuranceMapper.getInsuranceCount(mapParam);
		if (count <= 0) {
			return paged;
		}
		log.info("根据条件查询保险列表 入参：queryWrapper： " + JSON.toJSONString(mapParam));
		List<InsuranceBean> result = insuranceMapper.getInsurancePageList(mapParam, pageNum, pageSize);
		log.info("根据条件查询保险列表 出参：result： " + JSON.toJSONString(result));
		paged.setList(Convert.toInsuranceDto(result));
		paged.setTotal(count);
		paged.setPageSize(pageSize);
		return paged;
	}

	@Override
	public List<InsuranceDto> getInsurance(CarInsuranceTypeEnum insuranceEnum) {
		List<InsuranceBean> result = insuranceMapper.getInsuranceList(insuranceEnum.getValue());
		return Convert.toInsuranceDto(result);
	}

	@Override
	public InsuranceDto getCompulsoryInsuranceById(int compulsoryInsuranceId) {
		InsuranceBean insuranceBean = insuranceMapper.getById(compulsoryInsuranceId);
		return Convert.toInsuranceDto(insuranceBean);
	}

	@Override
	public Boolean modifyCompulsoryInsurance(InsuranceModifyDto modifyDto) {
		int result = insuranceMapper.modifyInsurance(Convert.toInsuranceBean(modifyDto));
		if (result > 0) {
			return true;
		}
		return false;
	}

	@Override
	public Boolean createInsurance(InsuranceCreateDto createDto) {
		InsuranceBean bean = new InsuranceBean();
		BeanUtils.copyProperties(createDto, bean);
		int result = insuranceMapper.createInsurance(bean);
		if (result > 0) {
			createDto.setId(bean.getId());
			return true;
		}
		return false;
	}

	@Override
	public List<InsuranceDto> getInsuranceByCarId(Integer carId, CarInsuranceTypeEnum carInsuranceTypeEnum) {
		Integer type = carInsuranceTypeEnum == null ? null : carInsuranceTypeEnum.getValue();
		return Convert.toInsuranceDto(insuranceMapper.getInsuranceByCarId(carId, type));
	}

	@Override
	public int getInsuranceTabCount(int type, int status) {
		return insuranceMapper.getInsuranceTabCount(type, status);
	}

	@Override
	public InsuranceDto getInsuranceByCode(String code) {
		return Convert.toInsuranceDto(insuranceMapper.getInsuranceByCode(code));
	}

	/**
	 * 根据车辆，获取此车辆最后一次投保（按照end_time倒序取最后一个）
	 * 
	 * @param carId
	 * @return
	 */
	@Override
	public InsuranceDto getLastInsuranceByCarIdAndType(Integer carId, Integer type) {
		return Convert.toInsuranceDto(insuranceMapper.getLastInsuranceByCarIdAndType(carId, type));
	}
	
	@Override
	public InsuranceDto getInsuranceByCarIdAndType(Integer carId, Integer type) {
		InsuranceBean bean = insuranceMapper.getLastInsuranceByCarIdAndType(carId, type);
		if(null == bean) {
			return null;
		}
		//保单结束时间
		LocalDate endTime = bean.getEndTime().toLocalDate();
		LocalDate now = LocalDate.now();
		if(now.isAfter(endTime)) {
			return null;
		}
		return Convert.toInsuranceDto(insuranceMapper.getLastInsuranceByCarIdAndType(carId, type));
	}

	@Override
	public Integer createImportInsurance(InsuranceCreateDto createDto) {
		InsuranceBean bean = new InsuranceBean();
		BeanUtils.copyProperties(createDto, bean);
		int result = insuranceMapper.createInsurance(bean);
		if (result > 0) {
			return bean.getId();
		}
		return 0;
	}

	/**
	 * 保险导出
	 * 
	 * @param mapParam
	 * @return
	 */
	@Override
	public List<InsuranceDto> getDownloadInsuranceList(Map<String, Object> mapParam) {
		List<InsuranceBean> result = insuranceMapper.getDownloadInsuranceList(mapParam);
		return Convert.toInsuranceDto(result);
	}

	/**
	 * 保险导出count
	 * 
	 * @param mapParam
	 * @return
	 */
	@Override
	public Long getDownloadInsuranceCount(Map<String, Object> mapParam) {
		return insuranceMapper.getDownloadInsuranceCount(mapParam);
	}

	/**
	 * 查询保险公司ids
	 * 
	 * @param selectParams
	 * @return
	 */
	@Override
	public List<Integer> getInsuranceCompanyIds(Map<String, Object> selectParams) {
		return insuranceMapper.getInsuranceCompanyIds(selectParams);
	}

	/**
	 * 查询保单pdf不为空的列表
	 *
	 * @return
	 */
	@Override
	public List<InsuranceDto> getInsuranceListImgIsNotNull() {
		List<InsuranceBean> result = insuranceMapper.getInsuranceListImgIsNotNull();
		return Convert.toInsuranceDto(result);
	}

	@Override
	public void createInsuranceImgByPdf() {
		log.info("根据保单pdf创建不存在的png图片");

		List<InsuranceDto> list = getInsuranceListImgIsNotNull();
		if (list != null && list.size() > 0) {
//
//			//		https://mlpublic.oss-cn-hangzhou.aliyuncs.com/insurance/LNBSCB3FXJW180682.pdf
			OSS ossClient = OssUtil.getOSSClient();
			for (InsuranceDto insuranceDto : list) {
				if (insuranceDto == null || StringUtils.isEmpty(insuranceDto.getInsureProve())) {
					continue;
				}

				String url = insuranceDto.getInsureProve();
				url = url.replace("https://", "");
				String bucket = url.substring(0, url.indexOf("."));
				String filename = url.substring(url.indexOf(".com/") + 5);
				String imgname = filename.substring(0, filename.lastIndexOf(".")) + ".png";

				boolean pdfFound = ossClient.doesObjectExist(bucket, filename);
				boolean imgFound = ossClient.doesObjectExist(bucket, imgname);

				if (pdfFound && !imgFound) {
					OSSObject o = ossClient.getObject(bucket, filename);
					InputStream inputStream = o.getObjectContent();
					ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
					try {
						PdfToImageUtil.pdfToImage(inputStream, outputStream);
						PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, imgname, new ByteArrayInputStream(outputStream.toByteArray()));
						PutObjectResult res = ossClient.putObject(putObjectRequest);
						log.info("创建保单图片："+imgname);
						inputStream.close();
						outputStream.close();
					} catch (IOException e) {
						log.error("根据pdf生产img文件，关闭流异常 >> "+e.getMessage());
						e.printStackTrace();
					}
				}
			}

			// 关闭OSSClient。
			ossClient.shutdown();
		}
	}
}
